package cn.uestc.labhms.modules.hms.service.impl;

import cn.uestc.labhms.modules.hms.dao.HmsChiEngDao;
import cn.uestc.labhms.modules.hms.dao.HmsUserPermDao;
import cn.uestc.labhms.modules.hms.entity.HmsUserPermEntity;
import cn.uestc.labhms.modules.hms.entity.Vo.UserPermsVo;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.service.UserPermService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Mu.tz
 */
@Service
public class UserPermServiceImpl extends ServiceImpl<HmsUserPermDao, HmsUserPermEntity> implements UserPermService {
    @Autowired
    private HmsChiEngDao hmsChiEngDao;

    @Override
    public List<String> getListPerm(Integer userId) {
        List<HmsUserPermEntity> hmsUserPermEntities = baseMapper.selectList(
                new QueryWrapper<HmsUserPermEntity>().eq("user_id", userId)
                        .likeLeft("permission", "list"));
        List<String> perms = new LinkedList<>();
        hmsUserPermEntities.forEach(hmsUserPermEntity -> {
            perms.add(hmsUserPermEntity.getPermission());
        });
        List<String> tableNames = this.perms2TableName(perms);
        return tableNames;
    }

    @Override
    public List<String> getUpdatePerm(Integer userId) {
        List<HmsUserPermEntity> hmsUserPermEntities = baseMapper.selectList(
                new QueryWrapper<HmsUserPermEntity>().eq("user_id", userId)
                        .likeLeft("permission", "update"));
        List<String> perms = new LinkedList<>();
        hmsUserPermEntities.forEach(hmsUserPermEntity -> {
            perms.add(hmsUserPermEntity.getPermission());
        });
        List<String> tableNames = this.perms2TableName(perms);
        return tableNames;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUserPerms(Integer userId, List<String> perms, String type) {
        if (ObjectUtils.isEmpty(perms)) {
            baseMapper.delete(new QueryWrapper<HmsUserPermEntity>().eq("user_id", userId));
            return;
        }
        baseMapper.delete(new QueryWrapper<HmsUserPermEntity>()
                .eq("user_id", userId)
                .likeLeft("permission", type)
                .ne("permission", "*:*:*"));
        List<HmsUserPermEntity> userPermEntities = new ArrayList<>(perms.size());
        perms.forEach(perm -> {
            String tableName = hmsChiEngDao.getTableNameC2E(perm);
            String permStr = "hms:" + tableName + ":" + type;
            HmsUserPermEntity hmsUserPermEntity = new HmsUserPermEntity();
            hmsUserPermEntity.setUserId(userId);
            hmsUserPermEntity.setPermission(permStr);
            userPermEntities.add(hmsUserPermEntity);
        });
        boolean flag = this.saveBatch(userPermEntities);
        if (!flag) {
            throw new HMSException("系统未知异常，权限修改失败");
        }
    }

    private List<String> perms2TableName(List<String> permissions) {
        List<String> tableNames = new LinkedList<>();
        permissions.forEach(permission -> {
            String[] split = permission.split(":");
            if (split.length > 2) {
                String tableNameE = split[1];
                String tableNameC = hmsChiEngDao.getTableNameE2C(tableNameE);
                if (ObjectUtils.isEmpty(tableNameC)) {
                    throw new HMSException("没有" + tableNameE + "对应的表");
                }
                tableNames.add(tableNameC);
            }
        });
        return tableNames;
    }
}
